package com.zbkj.crmeb.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonResult;
import com.exception.CrmebException;
import com.utils.DateUtil;
import com.zbkj.crmeb.user.dao.UserMarkDao;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.model.UserLevelGood;
import com.zbkj.crmeb.user.model.UserMark;
import com.zbkj.crmeb.user.model.UserMarkEnum;
import com.zbkj.crmeb.user.model.UserRelRecord;
import com.zbkj.crmeb.user.service.UserMarkService;
import com.zbkj.crmeb.user.service.UserRelRecordService;
import com.zbkj.crmeb.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * UserMarkServiceImpl 接口实现 +---------------------------------------------------------------------- | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +---------------------------------------------------------------------- | Copyright (c) 2016~2020 https://www.crmeb.com All rights
 * reserved. +---------------------------------------------------------------------- | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +---------------------------------------------------------------------- | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class UserMarkServiceImpl extends ServiceImpl<UserMarkDao, UserMark> implements UserMarkService {

    @Resource
    private UserMarkDao dao;
    @Resource
    private UserRelRecordService userRelRecordService;
    @Resource
    private UserService userService;

    @Override
    public UserMark getByUserId(Integer userId) {
        LambdaQueryWrapper<UserMark> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMark::getUserId, userId);
        return dao.selectOne(wrapper);
    }

    @Transactional
    @Override
    public void updateUserMark(Integer userId, UserLevelGood userLevelGood) {
        if (userId == null || userLevelGood == null) {
            return;
        }
        User user = userService.getById(userId);
        UserMark userMark = getByUserId(userId);
        if (userMark == null) {
            userMark = new UserMark();
            userMark.setUserId(userId);
            userMark.setMarkId(userLevelGood.getId());
            userMark.setMarkName(userLevelGood.getLevelName());
            userMark.setMarkTime(DateUtil.nowDateTime());
            dao.insert(userMark);
        } else {
            userMark.setMarkId(userLevelGood.getId());
            userMark.setMarkName(userLevelGood.getLevelName());
            userMark.setMarkTime(DateUtil.nowDateTime());
            dao.updateById(userMark);
        }
        // 更新用户等级
        user.setUserRankLevel(userLevelGood.getId());
        userService.updateById(user);
    }

}

